/**
 * 只在H5端使用
 * 获取商户id以及请求地址
 */

// 当前是否在获取最新的商户id和请求地址
let refresh = false;
// 是否获取成功 全局唯一 只获取一次
let isRequest = false;
// 最大获取次数
let maxRequestNum = 5;
// 当前请求次数
let requestNum = 0;
let uniacInfo = null;

export default function refreshUniacInfo() {
	return new Promise(async (resolve, reject) => {
		if (isRequest) {
			resolve(true);
		}
		if (!refresh) {
			uniacInfo = null;
			requestNum = 0;
			refresh = true;
			let data = await getUniacInfo();
			uniacInfo = data;
			getApp().globalData.url = data.other_url;
			getApp().globalData.urlimg = data.other_url + "/uploads/";
			getApp().globalData.imgUrl = data.other_url + "assets/api/images/";
			getApp().globalData.api_root = data.other_url + +"index.php?s=/api/";
			uni.setStorageSync("web_id", data.wxapp_id);

			if (data && typeof data == "object") {
				resolve(data);
			} else {
				resolve(false);
			}
		} else {
			clearInterval(timer);
			let timer = setInterval(() => {
				if (requestNum >= maxRequestNum) {
					resolve(false);
					clearInterval(timer);
				}
				if (uniacInfo) {
					clearInterval(timer);
					resolve(uniacInfo);
				}
			}, 10);
		}
	});
}

function getUniacInfo() {
	return new Promise((resolve, reject) => {
		_getUniacInfo();

		function _getUniacInfo() {
			uni.request({
				url: getApp().globalData.url +
					`index.php?s=api/user/getSiteUrl&wxapp_id=` + getApp().globalData.uniacid,
				data: {},
				method: "POST",
				header: {
					platform: "H5",
				},
				success(res) {
					if (res.data.code == 1) {
						isRequest = true;
						resolve(res.data.data);
					} else {
						error();
					}
				},

				fail() {
					error();
				},
			});
		}

		function error() {
			requestNum++;
			if (requestNum < maxRequestNum) {
				_getToken();
			} else if (requestNum >= maxRequestNum) {
				resolve(false);
			}
		}
	});
}
